import breaDcrumb from '@/components/breadcrumb';
import {
  mapGetters
} from 'vuex';
import {
  formatTreeData
} from '@/utils/utils'
import {
  queryPage as queryorganPage
} from '@/api/basedata/organization.js';
import {
  queryPage as queryjobsPage
} from '@/api/basedata/jobs.js';
import {
  queryPage as queryrolePage
} from '@/api/basedata/role.js';
import {
  queryPage as queryuserPage
} from '@/api/basedata/user';
import {
  queryPage as querybusinessPage
} from '@/api/basedata/business.js';
import {
  saveOrUpdate,
  queryIds,
  functionTree,
  get_system_function_buttonByuser,
  get_table_title,
  query_table_data,
  save_or_update,
  get_data_limits_settings,
  queryIds1,
  get_data_limits_second_settings,
  get_data_limits_table_settings

} from '@/api/basedata/permissions.js';
import styles from '@/app.scss';
import { Loading } from 'element-ui';
import {
  queryPage as queryDataAccessPage
} from '@/api/basedata/DataAccess.js';
import { getUserInfo } from "@/utils/auth.js";
let jobslist = []
let userlist = []
let rolelist = []
export default {
  components: {
    breaDcrumb,
  },
  data() {
    return {
      bg_color: styles.bg_color,
      currrenIndex: 1,
      leftList: [{
        text: '组织',
        value: 'organization'
      }, {
        text: '岗位',
        value: 'station'
      }, {
        text: '用户',
        value: 'user'
      }, {
        text: '角色',
        value: 'role'
      }],
      leftIndex: 'user',
      rightList: [{
        text: '功能权限',
        value: 1
      }, {
        text: '数据权限',
        value: 5
      },
      {
        text: 'App权限',
        value: 2
      }, {
        text: '微信小程序权限',
        value: 3
      }],
      rightIndex: 1,
      treearr: [],
      treearrIds: [],
      treearrId: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      josarr: [],
      jobsinput: '',
      jobIds: [],
      jobsId: '',
      jobsIndex: null,
      rolearr: [],
      roleinput: '',
      roleIds: [],
      roleId: '',
      roleIndex: null,
      userarr: [],
      userinput: '',
      userIds: [],
      userId: '',
      userIndex: null,
      functiontreeData: [],
      loading: false,
      /*数据权限详细列表*/
      newtree: [],
      tableData: [],
      allTableData: [],
      table: '',
      tableTitle: [],
      functionId: '',
      shujucheckarr: [],
      shujucheckarrarr: [],
      rightloading: false,
      leftloading: false,
      timer: '',
      radio: '',
      radio1: '',
      show: '',
      tree1: '',
      tableShow: [],
      foreignId: '',
      choiseId: '',
      searchValue: '',
    };
  },
  watch: {
    userinput() {
      this.userarr = new Array();
      if (this.userinput == '') {
        this.userarr = userlist;
      } else {
        userlist.forEach(item => {
          if (item.name.indexOf(this.userinput) !== -1) {
            this.userarr.push(item);
          }
        });
      }
    },
    jobsinput() {
      this.josarr = new Array();
      if (this.jobsinput == '') {
        this.josarr = jobslist;
      } else {
        jobslist.forEach(item => {
          if (item.name.indexOf(this.jobsinput) !== -1) {
            this.josarr.push(item);
          }
        });
      }
    },
    roleinput() {
      this.rolearr = new Array();
      if (this.roleinput == '') {
        this.rolearr = rolelist;
      } else {
        rolelist.forEach(item => {
          if (item.name.indexOf(this.roleinput) !== -1) {
            this.rolearr.push(item);
          }
        });
      }
    },
    searchValue: {
      deep: true,
      handler() {
        this.debounce(this.changeValue, 2000)
      }
    }
  },
  async mounted() {
    this.rightloading = true
    this.leftloading = true
    const params = {
      page: 1,
      pageSize: 10000,
    }
    /*获取组织*/
    await queryorganPage({
      ...params,
      showEnable: 0
    }).then(res => {
      if (res.code === 1001) {
        const {
          data
        } = res.data;
        this.treearr = formatTreeData(data, 'id', 'parentId', 'children', 'parent_id');
      }
    })
    /*获取岗位*/
    await queryjobsPage({
      ...params,
      enable: 1
    }).then(res => {
      jobslist = JSON.parse(JSON.stringify(res.data.data))
      this.josarr = JSON.parse(JSON.stringify(res.data.data))

    });
    /*获取角色*/
    await queryrolePage({
      ...params,
      roleEentrance: 'entrance_manager',
      enable: 1
    }).then(res => {
      rolelist = JSON.parse(JSON.stringify(res.data.data))
      this.rolearr = JSON.parse(JSON.stringify(res.data.data))
    })
    /*获取用户*/
    await queryuserPage({
      ...params,
      userEentrance: 'entrance_manager',
      enable: 1
    }).then(res => {
      userlist = JSON.parse(JSON.stringify(res.data.data))
      this.userarr = JSON.parse(JSON.stringify(res.data.data))
    })
    this.leftloading = false
    /*获取功能树*/
    this.changetight(1)
    /*获取数据权限系统树*/
    await querybusinessPage(params).then(res => {
      res.data.data.forEach(item => {
        item.children = [];
        item.hierarchytyp = 'system';
      });
      this.newtree = res.data.data
      let arr = []
      queryDataAccessPage(params).then(res => {
        arr = res.data.data.map(item => {
          item.icon = 'iconfont icontree_icon_text'
          return item
        })
        this.newtree.forEach(b => {
          b.request = 1
          for (let c in arr) {
            if (b.id == arr[c].systemId) {
              b.children.push(arr[c])
            }
          }
        })
      })
    });
  },
  methods: {
    debounce(fn, wait) {
      if (this.timer !== null) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(fn, wait)
    },
    changeValue() {
      if (this.searchValue === '') {
        this.tableData = this.allTableData;
      } else {
        this.tableData = this.allTableData.filter(item => this.tableTitle.some(items => (item[items.columnName])?.indexOf(this.searchValue) > -1));
      }
      /**
       * @Description: 设置选中
       * @param {*} rows
       * @Author: wangwangwang
       */
      let data1 = {
        dataLimitsJoinId: this.table.id,
        foreignId: this.getforeignId(),
        foreignType: this.leftIndex,
      }
      /*获取表回显*/
      get_data_limits_table_settings(data1).then(res => {
        this.tableShow = res.data;
        let rows = this.tableShow.map(res => {
          let index = this.tableData.findIndex(item => (item.ID == res.dataId))
          return this.tableData[index]
        })
        rows = rows.filter(d => d)
        this.toggleSelection(rows)
      })
    },
    /*
     *数据权限
     */
    /**数据权限里系统回显*/
    getshuju(id) {
      this.radio = ''
      this.tableData = []
      this.tree1 = new Date().getTime()
      get_data_limits_settings({
        foreignId: id,
        foreignType: this.leftIndex
      }).then(res => {
        this.show = res.data
      })
    },
    /*获取数据权限表*/
    async gettable(data) {
      let _this = this
      _this.tableShow = []
      if (!_this.getforeignId()) {
        _this.$message({
          message: '警告哦，清请在左侧选择要关联的数据',
          type: 'warning'
        });
        return
      }
      /*获取表头数据*/
      _this.table = data
      await get_table_title({
        dataLimitsId: data.id
      }).then(res => {
        _this.tableTitle = res.data
      })
      let params = {
        page: 1,
        pageSize: 99999,
        id: _this.table.id,
        systemId: _this.table.systemId,
        tableName: _this.table.tableName,
        foreignType: _this.leftIndex,
        foreignId: _this.getforeignId(),
      }
      /*获取表、数据*/
      await query_table_data(params).then(res => {
        _this.tableData = res.data.data;
        _this.allTableData = res.data.data;
      })
      let data1 = {
        dataLimitsJoinId: data.id,
        foreignId: _this.getforeignId(),
        foreignType: _this.leftIndex,
      }
      /*获取表回显*/
      await get_data_limits_table_settings(data1).then(res => {
        _this.tableShow = res.data;
      })
      let rows = _this.tableShow.map(res => {
        let index = _this.tableData.findIndex(item => (item.ID == res.dataId))
        return _this.tableData[index]
      })
      rows = rows.filter(d => d)

      await _this.toggleSelection(rows)
      // this.tableData.forEach(res => {
      //   if (this.tableShow.findIndex(item => (item.dataId == res.ID)) !== -1) {
      //     res.checkStatus = 1
      //   }
      // })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      }
    },
    /*选择后绑定数据权限表*/
    multipleTableFun(val) {
      let allHasData = this.tableShow.filter((item) => (
        val.some((items) => (item.dataId == items.ID))
      ))
      let deleteData = this.tableShow.filter((item) => (
        !allHasData.some((items) => (item.dataId == items.dataId))
      ))
      console.log(JSON.parse(JSON.stringify(deleteData)))
      let addData = val.filter((item) => (
        !allHasData.some((items) => (item.ID == items.dataId))
      ))
      deleteData = deleteData.map(res => (
        {
          tableName: this.table.tableName,
          status: 0,
          id: res.id,
          dataId: res.dataId,
        }
      ))
      addData = addData.map(res => ({
        tableName: this.table.tableName,
        status: 1,
        dataId: res.ID,
      }))
      let dataLimitsDataList = [...deleteData, ...addData]
      console.log(dataLimitsDataList);
      let arr = [{
        foreignType: this.leftIndex,
        foreignId: this.getforeignId(),
        systemId: this.table.systemId,
        tableName: this.table.tableName,
        dataLimitsId: this.table.id,
        dataLimitsDataList: dataLimitsDataList
      }]
      let loadingInstance = Loading.service({ text: '数据授权中...' });
      save_or_update(arr).then(async () => {
        loadingInstance.close();
      })
    },
    /*
     *数据权限快捷配置
     *数据表数据
     */
    /**获取数据表*/
    async gettable1(data) {
      /*获取表数据*/
      this.table = data
      await get_table_title({
        dataLimitsId: data.id
      }).then(res => {
        this.tableTitle = res.data
      })
      let params = {
        page: 1,
        pageSize: 99999,
        id: data.id,
        tableName: data.tableName,
        foreignType: this.leftIndex,
        foreignId: this.getforeignId(),
      }
      await query_table_data(params).then(res => {
        this.tableData = res.data.data
        this.allTableData = res.data.data;
        this.show = []
        this.radio1 = ''
        if (this.leftIndex == "organization") {
          this.$refs.tree.setCheckedKeys([])
        }
        if (this.leftIndex == "station") {
          this.jobIds = []
        }
        if (this.leftIndex == "user") {
          this.userIds = []
        }
        if (this.leftIndex == "role") {
          this.roleIds = []
        }
      })
    },
    /**获取数据回显*/
    async getshuju1(ID) {
      let data = {
        foreignType: this.leftIndex,
        systemId: this.table.systemId,
        tableName: this.table.tableName,
        dataId: ID,
        dataLimitsId: this.table.id
      }
      await get_data_limits_second_settings(data).then(res => {
        this.show = res.data

        let arr = res.data.map(res => (res.dataId))
        if (this.leftIndex == "organization") {
          this.$refs.tree.setCheckedKeys(arr)
        }
        if (this.leftIndex == "station") {
          this.jobIds = arr
        }
        if (this.leftIndex == "user") {
          this.userIds = arr
        }
        if (this.leftIndex == "role") {
          this.roleIds = arr
        }
      })
    },
    /**绑定数据权限*/
    handleSelectionChange1(key) {
      let _this = this
      if (!_this.table) {
        this.$message({
          message: '警告哦，请在左侧选择要关联的数据权限',
          type: 'warning'
        });
        return
      }
      let loadingInstance = Loading.service({ text: '数据授权中...' });
      let allkey = _this.show.filter((item) => (
        key.some((items) => (item.dataId == items))
      ))
      let addData = key.filter(item => (
        !allkey.some((items) => (item == items.dataId))
      ))
      let delData = _this.show.filter(item => (
        !allkey.some((items) => (item.dataId == items.dataId))
      ))
      addData = addData.map(res => {
        let obj = {
          foreignType: _this.leftIndex,
          foreignId: res,
          systemId: _this.table.systemId,
          tableName: _this.table.tableName,
          dataLimitsId: _this.table.id,
          dataLimitsDataList: [{
            tableName: _this.table.tableName,
            status: 1,
            dataId: _this.radio1,
          }]
        }
        return obj
      })
      delData = delData.map(res => {
        let obj = {
          foreignType: _this.leftIndex,
          foreignId: res.dataId,
          systemId: _this.table.systemId,
          tableName: _this.table.tableName,
          dataLimitsId: _this.table.id,
          dataLimitsDataList: [{
            tableName: _this.table.tableName,
            status: 0,
            dataId: _this.radio1,
            id: res.id
          }]
        }
        return obj
      })
      let arr = [...delData, ...addData]
      console.log(arr)
      console.log(2);
      save_or_update(arr).then(async () => {
        await this.getshuju1(this.radio1)
        loadingInstance.close()
      })
    },
    /*
     *权限配置
     *快捷配置与配置切换，充值数据
     */
    choosecurrrenIndex(num) {
      this.init()
      this.currrenIndex = num
    },
    /*重置动态数据*/
    init() {
      this.jobsId = ''
      this.jobsIndex = null
      this.jobIds = []
      this.roleId = ''
      this.roleIndex = null
      this.roleIds = []
      this.userId = ''
      this.userIndex = null
      this.userIds = []
      this.timer = new Date().getTime()
      this.treearrId = ''
      this.checkkey = []
      this.tableData = []
      this.show = []
      this.tree1 = new Date().getTime()
      // this.$refs.functiontree.setCheckedKeys([])
      // this.$refs.tree.setCheckedKeys([])
      this.radio = ''
      this.radio1 = ''
      this.jobsinput = ''
      this.userinput = ''
      this.roleinput = ''

    },
    /*右侧导航*/
    changetight(num) {
      this.rightloading = true
      this.functiontreeData = []
      this.rightIndex = num;
      this.searchValue = '';
      if (num !== 5) {
        let TreeUrl = get_system_function_buttonByuser
        if (getUserInfo().adminStatus == 1) {
          TreeUrl = functionTree
        }
        // TreeUrl = functionTree
        TreeUrl({
          type: this.rightIndex
        }).then(res => {
          res.data.forEach(res => {
            let arr = []
            arr.push(res.parentId)
            arr.push(res.id)
            res.nodeId = arr.join(',')
          })
          const {
            data
          } = res;
          console.log(data);
          if (num == 2) { // 2 APP、3小程序
            let Array = formatTreeData(data, 'id', 'parentId', 'children', 'parent_id');
            if (getUserInfo().adminStatus == 1) {
              this.functiontreeData = Array[1]?.children[0]?.children;
            } else {
              this.functiontreeData = Array
            }
            console.log(JSON.parse(JSON.stringify(this.functiontreeData)), '二')
          } else if (num == 3) {
            let Array = formatTreeData(data, 'id', 'parentId', 'children', 'parent_id');
            this.functiontreeData = Array[0]?.children
            console.log(JSON.parse(JSON.stringify(this.functiontreeData)), '三')
          } else {
            this.functiontreeData = formatTreeData(data, 'id', 'parentId', 'children', 'parent_id');
            console.log(JSON.parse(JSON.stringify(this.functiontreeData)), '一')
          }

          this.rightloading = false
          this.getcheckbutton(this.choiseId)
        })
      } else {
        if (this.table) {
          this.gettable(this.table)
        }
        this.rightloading = false
      }
    },
    /*左侧导航*/
    async changeleft(value) {
      this.choiseId = '';
      this.leftIndex = value;
      this.leftloading = true;
      await this.init()
      this.leftloading = false;
    },
    /*
     *权限配置--功能权限
     *获取对应得组织，岗位，用户，角色id
     */
    getforeignId() {
      let foreignId = ''
      if (this.leftIndex == 'organization') {
        foreignId = this.treearrId
      }
      if (this.leftIndex == 'station') {
        foreignId = this.jobsId
      }
      if (this.leftIndex == 'user') {
        foreignId = this.userId
      }
      if (this.leftIndex == 'role') {
        foreignId = this.roleId
      }
      return foreignId
    },

    /*组织ID*/
    setTree(e) {
      this.treearrId = e.id;
      this.choiseId = e.id;
      if (this.rightIndex == '5') {
        this.getshuju(e.id)
      } else {
        this.getcheckbutton(e.id)
      }

    },
    /*岗位ID*/
    choosejob(item) {
      this.jobsIndex = item.id;
      this.jobsId = item.id;
      this.choiseId = item.id;
      if (this.rightIndex == '5') {
        this.getshuju(item.id)
      } else {
        this.getcheckbutton(item.id)
        console.log(2);
      }
    },
    /*用户ID*/
    chooseuser(item) {
      this.userIndex = item.id;
      this.userId = item.id;
      this.choiseId = item.id;
      if (this.rightIndex == '5') {
        this.getshuju(item.id)
      } else {
        this.getcheckbutton(item.id)
      }
    },
    /*角色ID*/
    chooserole(item) {
      this.roleIndex = item.id;
      this.roleId = item.id;
      this.choiseId = item.id;
      if (this.rightIndex == '5') {
        this.getshuju(item.id)
      } else {
        this.getcheckbutton(item.id)
      }
    },
    /*获取绑定的按钮*/
    async getcheckbutton(foreignId) {
      if (foreignId) {
        this.rightloading = true
        let params = {
          foreignType: this.leftIndex,
          foreignId: foreignId,
          type: this.rightIndex
        }
        await queryIds(params).then(res => {
          res.data.forEach(res => {
            let arr = []
            arr.push(res.functionId)
            arr.push(res.buttonId)
            res.nodeId = arr.join(',')
          })
          this.checkkey = res.data
          let key = []
          res.data.forEach(item => {
            key.push(item.nodeId)
          })
          this.$refs.functiontree.setCheckedKeys(key)
          this.rightloading = false
        })
      }
    },
    /*保存功能权限*/
    getButton() {
      if (!this.getforeignId()) {
        this.$message({
          message: '警告哦，清请在左侧选择要关联的数据',
          type: 'warning'
        });
        this.init()
        return
      }
      let keys = this.$refs.functiontree.getCheckedNodes()
      let data = []
      let newkeys = []
      newkeys = keys.filter(item => {
        return !item.children
      })
      if (this.checkkey) {
        let loadingInstance = Loading.service({ text: '授权中...' });
        let allHasData = this.checkkey.filter((item) => (
          newkeys.some((items) => (item.buttonId === items.id && item.functionId == items.parentId))
        ))
        allHasData.map((res) => {
          res.status = 1
        })
        let deleteData = this.checkkey.filter((item) => (
          !allHasData.some((items) => (item.buttonId === items.buttonId && item.functionId == items.functionId))
        ))
        let addData = newkeys.filter((item) => (
          !allHasData.some((items) => (item.id === items.buttonId && item.parentId == items.functionId))
        ))
        deleteData = deleteData.map(res => {
          let obj = new Object()
          obj.type = res.type
          obj.foreignType = res.foreignType
          obj.foreignId = res.foreignId
          obj.buttonId = res.buttonId
          obj.buttonName = res.buttonName
          obj.functionId = res.functionId
          obj.status = 0
          obj.id = res.id
          return obj
        })
        addData = addData.map(item => {
          let obj = new Object()
          obj.type = this.rightIndex
          obj.foreignType = this.leftIndex
          obj.foreignId = this.getforeignId()
          obj.buttonId = item.id
          obj.buttonName = item.name
          obj.functionId = item.parentId
          obj.status = 1
          return obj
        })
        data = [...deleteData, ...addData]
        console.log(JSON.parse(JSON.stringify(addData)), '最终数据addData')
        console.log(JSON.parse(JSON.stringify(deleteData)), '最终数据deleteData')
        // console.log(JSON.parse(JSON.stringify(data)), '最终数据')
        // console.log(saveOrUpdate);
        saveOrUpdate(data).then(async () => {
          await this.getcheckbutton(this.getforeignId())
          loadingInstance.close()
        })
      }
    },
    /*
     *权限快捷配置--功能权限
     *获取功能Id
     */
    async changefunction(e) {
      let params = {
        foreignType: this.leftIndex,
        buttonId: e.id,
        type: this.rightIndex,
        functionId: e.parentId
      }
      await queryIds1(params).then(res => {
        console.log(res.data)
        this.checkkey = res.data
        if (this.rightIndex !== 5) {
          let key = []
          res.data.forEach(item => {
            key.push(item.foreignId)
          })
          if (this.leftIndex == 'organization') {
            this.$refs.tree.setCheckedKeys(key)
          } else if (this.leftIndex == 'station') {
            this.jobIds = key
          } else if (this.leftIndex == 'user') {
            this.userIds = key
          } else {
            this.roleIds = key
          }
        } else {
          console.log('数据')
        }
      })
    },
    /*
     *保存对应关系
     */
    submit1() {
      let key = []
      if (this.leftIndex == 'organization') {
        key = this.$refs.tree.getCheckedKeys()
      } else if (this.leftIndex == 'station') {
        key = this.jobIds
      } else if (this.leftIndex == 'user') {
        key = this.userIds
      } else {
        key = this.roleIds
      }
      if (this.rightIndex !== 5) {
        if (!this.foreignId) {
          this.$message({
            message: '警告哦，请先选择左侧权限',
            type: 'warning'
          });
          this.init()
          return
        }
        let loadingInstance = Loading.service({ text: '授权中...' });
        let allHasData = this.checkkey.filter((item) => (
          key.some((items) => (item.foreignId === items))
        ))
        let deleteData = this.checkkey.filter((item) => (
          !allHasData.some((items) => item.foreignId === items.foreignId)))

        let addData = key.filter((item) => (
          !allHasData.some((items) => (item === items.foreignId))
        ))
        allHasData = allHasData.map(res => {
          let obj = new Object()
          obj.type = res.type
          obj.foreignType = res.foreignType
          obj.foreignId = res.foreignId
          obj.buttonId = res.buttonId
          obj.buttonName = res.buttonName
          obj.functionId = res.functionId
          obj.status = 1
          obj.id = res.id
          return obj
        })
        deleteData = deleteData.map(res => {
          let obj = new Object()
          obj.type = res.type
          obj.foreignType = res.foreignType
          obj.foreignId = res.foreignId
          obj.buttonId = res.buttonId
          obj.buttonName = res.buttonName
          obj.functionId = res.functionId
          obj.status = 0
          obj.id = res.id
          return obj
        })
        addData = addData.map(res => {
          let obj = new Object()
          obj.type = this.rightIndex
          obj.foreignType = this.leftIndex
          obj.foreignId = res
          obj.buttonId = this.foreignId.id
          obj.buttonName = this.foreignId.name
          obj.functionId = this.foreignId.parentId
          obj.status = 1
          return obj
        })
        //...allHasData
        let data = [...deleteData, ...addData]
        saveOrUpdate(data).then(async () => {
          await this.changefunction(this.foreignId)
          loadingInstance.close()
        })
      } else {
        this.handleSelectionChange1(key)
      }
    },
  },
  computed: {
    ...mapGetters({
      screenWidth: 'getscreenWidth',
      screenHeight: 'getscreenHeight',
      Collapse: 'getsCollapse',
    }),
    style() {
      let num = 0;
      if (this.Collapse) {
        num = this.screenWidth - 124;
      } else {
        num = this.screenWidth - 220;
      }
      return 'width:' + num + 'px;';
    },

  }
};